﻿using System;
using log4net;
using Matrix.MaKaYunShang.Model.Wechat;
using Matrix.Common.Utility;
using Newtonsoft.Json;

namespace Matrix.MaKaYunShang.BLL.WxInterfaceFunc
{
    public class WxInterUserFunc : BaseWxInterFunc
    {
        private readonly ILog _fileLog = LogManager.GetLogger(typeof(WxInterUserFunc));


        #region 微信网页授权获取用户基本信息

        /// <summary>
        ///     获取网页授权的ACCESS_TOKEN
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <param name="authCode"></param>
        /// <returns></returns>
        public OAuthToken GetWebOAuthAccessToken(string appId, string appSecret, string authCode)
        {
            const string strInterfaceUrl =
                "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
            var strRequestUrl = string.Format(strInterfaceUrl, appId, appSecret, authCode);

            var strJson = GetHttpsInterfaceWebContent(strRequestUrl);

            if (string.IsNullOrWhiteSpace(strJson)) return null;
            var oAuthToken = JsonTool.JsonToObj<OAuthToken>(strJson);
            return oAuthToken;
        }

        /// <summary>
        ///     刷新access_token
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="refreshToken"></param>
        /// <returns></returns>
        public OAuthToken GetWebOAuthTokenByRefreshToken(string appId, string refreshToken)
        {
            const string strInterfaceUrl =
                "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}";
            string strRequestUrl = string.Format(strInterfaceUrl, appId, refreshToken);

            string strJson = GetHttpsInterfaceWebContent(strRequestUrl);

            if (string.IsNullOrWhiteSpace(strJson)) return null;
            var oAuthToken = JsonTool.JsonToObj<OAuthToken>(strJson);
            return oAuthToken;
        }

        /// <summary>
        ///     检验授权凭证（access_token）是否有效
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openId"></param>
        /// <returns></returns>
        public bool CheckWebAuthAccessTokenValid(string accessToken, string openId)
        {
            const string strInterfaceUrl = "https://api.weixin.qq.com/sns/auth?access_token={0}&openid={1}";
            string strRequestUrl = string.Format(strInterfaceUrl, accessToken, openId);

            string strJson = GetHttpsInterfaceWebContent(strRequestUrl);

            var errorCode = JsonTool.JsonToObj<WxResultCommonMsg>(strJson);
            if (errorCode.errcode != 0)
            {
                throw new Exception(strJson);
            }
            return true;
        }

        /// <summary>
        ///     获取网页授权的用户信息，若ACCESS_TOKEN超时失效，则刷新一次
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <param name="accessToken"></param>
        /// <param name="openId"></param>
        /// <param name="refreshToken"></param>
        /// <param name="tokenKey"></param>
        /// <returns></returns>
        public WxUserInfo GetWebOAuthUserInfo(string appId, string appSecret, string accessToken, string openId,
            string refreshToken)
        {
            //判断ACCESS_TOKEN超时，刷新ACCESS_TOKEN
            var oauthTokenRefresh = GetWebOAuthTokenByRefreshToken(appId, refreshToken);

            const string strInterfaceUrl =
                "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
            var strRequestUrl = string.Format(strInterfaceUrl, oauthTokenRefresh.access_token,
                oauthTokenRefresh.openid);
            var strJson = ClientHelper.GetWebContent(strRequestUrl);
            if (string.IsNullOrWhiteSpace(strJson))
                throw new WxErrorMsgException("The result value of interface is empty",
                    WxErrorMsgExceptionType.CloudCustomerException);
            if (strJson.Contains("\"errcode\":") && strJson.Contains("\"errmsg\":"))
            {
                throw new WxErrorMsgException(strJson, WxErrorMsgExceptionType.WxErrorException);
            }

            _fileLog.Info("WxInterUserFunc | GetWebOAuthUserInfo : " + strJson);
            var oAuthUser = JsonConvert.DeserializeObject<WxUserInfo>(strJson);

            return oAuthUser;
        }

        /// <summary>
        ///     获取网页授权用户信息
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <param name="authCode"></param>
        /// <param name="tokeKey"></param>
        /// <returns></returns>
        public WxUserInfo GetWebAuthTokenUserInfo(string appId, string appSecret, string authCode)
        {
            var oauthToken = GetWebOAuthAccessToken(appId, appSecret, authCode);
            if (oauthToken == null)
                return null;

            var oauthUser = GetWebOAuthUserInfo(appId, appSecret, oauthToken.access_token, oauthToken.openid,
                oauthToken.refresh_token);

            if (oauthUser == null)
                return null;

            return oauthUser;
        }

        /// <summary>
        ///     获取网页授权的用户信息，若ACCESS_TOKEN超时失效，则刷新一次 JSON
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="accessToken"></param>
        /// <param name="openId"></param>
        /// <param name="refreshToken"></param>
        /// <returns></returns>
        public string GetWebOAuthUserInfoJson(string appId, string accessToken, string openId, string refreshToken)
        {
            const string strInterfaceUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";

            //判断ACCESS_TOKEN超时，刷新ACCESS_TOKEN
            var oauthTokenRefresh = GetWebOAuthTokenByRefreshToken(appId, refreshToken);
            var strRequestUrl = string.Format(strInterfaceUrl, oauthTokenRefresh.access_token,
                oauthTokenRefresh.openid);
            var strJson = ClientHelper.GetWebContent(strRequestUrl);
            if (string.IsNullOrWhiteSpace(strJson))
                throw new WxErrorMsgException("The result value of interface is empty",
                    WxErrorMsgExceptionType.CloudCustomerException);
            if (strJson.Contains("\"errcode\":") && strJson.Contains("\"errmsg\":"))
            {
                throw new WxErrorMsgException(strJson, WxErrorMsgExceptionType.WxErrorException);
            }


            return strJson;
        }

        /// <summary>
        ///     获取网页授权用户信息 json
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <param name="authCode"></param>
        /// <returns></returns>
        public string GetWebAuthTokenUserInfoJson(string appId, string appSecret, string authCode)
        {
            var oauthToken = GetWebOAuthAccessToken(appId, appSecret, authCode);
            if (oauthToken == null)
                return null;

            var oauthUser = GetWebOAuthUserInfoJson(appId, oauthToken.access_token, oauthToken.openid,
                oauthToken.refresh_token);

            if (oauthUser == null)
                return null;

            return oauthUser;
        }

        #endregion
    }
}
  